package com.myorg.search;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.myorg.service.FakeEmailGenerationService;
import com.myorg.service.StartupService;
import com.myorg.util.ConstantsToBeExternalized;

@ManagedBean
@ViewScoped
public class GenerateEmailFileBean implements Serializable {
	private static final long serialVersionUID = -8906867347702673488L;
	final static private Logger logger = LoggerFactory.getLogger(GenerateEmailFileBean.class);
	private String generateFilePath;
	private int generateFileSizInM = 5;
	private boolean compress;

	public String getGenerateFilePath() {
		return generateFilePath;
	}

	public void setGenerateFilePath(String generateFilePath) {
		this.generateFilePath = generateFilePath;
	}

	public int getGenerateFileSizInM() {
		return generateFileSizInM;
	}

	public void setGenerateFileSizInM(int generateFileSizInM) {
		this.generateFileSizInM = generateFileSizInM;
	}

	public boolean isCompress() {
		return compress;
	}

	public void setCompress(boolean compress) {
		this.compress = compress;
	}

	private String normalizeFileExtension(String path) {
		String capPath = path.toUpperCase();
		if (capPath.endsWith(".TXT.GZIP")) {
			return path.substring(0, path.length() - ".TXT.GZIP".length()) + (compress ? ".txt.gzip" : ".txt");
		} else if (capPath.endsWith(".TXT")) {
			return path.substring(0, path.length() - ".TXT".length()) + (compress ? ".txt.gzip" : ".txt");
		} else {
			return path + (compress ? ".txt.gzip" : ".txt");
		}
	}

	private String calcFilePath() {
		if (generateFilePath != null) {
			String p = generateFilePath.trim();
			if (p.startsWith("/")) {
				return p;
			} else {
				return ConstantsToBeExternalized.DEFAULT_DIR_FILES_UPLOAD + "/" + p;
			}
		}
		return null;
	}

	public void generateFakeEmailFile() {
		logger.info("Generating fake email file: " + generateFilePath);
		StartupService.touch();
		if (!StringUtil.isBlank(generateFilePath) && generateFileSizInM > 0) {
			new FakeEmailGenerationService().generateFakeEmails(generateFileSizInM * 1024L * 1024L, compress,
					normalizeFileExtension(calcFilePath()));
		}
	}
}
